<?php
namespace app\index\controller;

use app\index\model\YingMu;
use think\Controller;
use app\index\model\Member as Members;
use app\index\model\Sendcode;
use app\index\model\Addonarticle;
use app\index\model\Lookinto;
use app\index\model\TokenUser;
use think\Db;
use expand\Yunst;

class Login extends Common
{
    public function _initialize(){
        parent::_initialize();
		if(!in_array(ACTION_NAME,['logout'])){
			if(CheckMemberLogin()){
				$this->redirect('Member/index');
			}
		}
    }
    
    public function index()
    {
        $data=input('get.');
        if($data){
            $this->redirect('/login/register/invite/'.$data['invite_key']);
        }
		$this->assign('ac','login');
		return $this->fetch();
    }

    public function register()
    {
		if(request()->isAjax()){
			$mModel = new Members;
			$data = input('post.');
			$member = $mModel->where(['mobile'=>$data['mobile']])->find();
			if($member){
				return ajaxReturn('该手机号已注册');
			}
			if(session('mobilecode') != $data['mobile_code'] || session($data['mobile']) != $data['mobile_code']){
				return ajaxReturn('验证码与手机号不匹配');
			}
			if(!empty($data['invite'])){
				$parentId = $mModel->where(['invite'=>$data['invite']])->value('id');
				if(!$parentId){
					return ajaxReturn('邀请码不正确');
				}
				$data['parentId'] = $parentId;
			}else{
                return ajaxReturn('请通过邀请码注册');
            }
			$data['is_disable'] = 1;
			Db::startTrans();
			try{
				$result = $mModel->allowField(true)->save($data);
				$userId = $mModel->getLastInsID();
				if($result && $userId){
					Db::commit();
					$info = $mModel->where(['id'=>$userId])->find();
					session('UID',$info['id']);
					session('userName',$info['username']);
					session('mobile',$info['mobile']);
					session($info['mobile'],null);
					// 同步影沐会员数据
//					$ym_model = new YingMu();
//					$member_info = $mModel->where(['mobile'=>$data['mobile']])->find();
//					$ym_model->insertYingMuMember($member_info);
					return ajaxReturn('注册成功',url('Member/index'));
				}else{
					return ajaxReturn($mModel->getError());
				}
			}catch (\Exception $e) {
				// 回滚事务
				Db::rollback();
				return ajaxReturn($e->getMessage());
			}
		}else{
			$this->assign('ac','register');
		    return $this->fetch('index');
		}
    }

    public function agreement(){
//		$artModel = new Addonarticle();
//		$article = $artModel->where(['id'=>6])->value('content');
//		return html_entity_decode($article);
        return $this->fetch('agreement');
    }

    public function service(){
        return $this->fetch('service');
    }

    public function warning(){
        return $this->fetch('warning');
    }

    public function dzqm(){
        return $this->fetch('dzqm');
    }

    public function wtqm(){
        return $this->fetch('wtqm');
    }

    public function loginin(){
		if(request()->isAjax()){
			$data = input('post.');
			$mModel = new Members;
			$lookModel = new Lookinto();
			$tkModel = new TokenUser();
				if(!captcha_check($data['code'])){
					return ajaxReturn('图形验证码不正确');
				}
			$data['mobile'] = base64_decode($data['lockm']);
			$member = $mModel->where(['mobile'=>$data['mobile']])->find();
			if(empty($member)){
				return ajaxReturn('用户不存在');
			}
			if($member['is_disable']!=1){
				return ajaxReturn('账号被禁');
			}

			$data['password'] = base64_decode($data['lockcode']);
			if(md5($data['password'])!=$member['password'] && md5(md5($data['password']))!=$member['password'] && !password_verify($data['password'],$member['password'])){

			    return ajaxReturn('密码错误');

			}else{
				$user_token = $tkModel->createToken($member['id'], 2, 3600);
				session('member_token', $user_token);
				session('UID',$member['id']);
				session('userName',$member['username']);
				session('mobile',$member['mobile']);
                session('isCheck',$member['is_check']);
				$upData = ['last_time'=>$member['last2_time'],'last2_time'=>time()];
				if(empty($member['invite'])){
					$upData['invite'] = Getinvite();
				}
				$mModel->where(['id'=>$member['id']])->update($upData);
				return ajaxReturn('登录成功',url('index/index'));
			}
		}
	}
	public function logout(){
		session('UID',null);
		session('userName',null);
		session('mobile',null);
		session('member_token',null);
		return redirect('Index/index');
	}
	public function findpassword(){
		$token = input('token');
		$mobile = session($token);
		if(!empty($mobile)){
			$this->assign('mobile',$mobile);
			$this->assign('token',$token);
			return $this->fetch('findpassword2');
		}else{
			return $this->fetch();
		}
	}
	
	public function getpwdcode(){
		if(request()->isAjax()){
			$mobile = input('post.mobile');
			if(!captcha_check(input('post.code'))){
				return ajaxReturn('图形验证码不正确');
			}
			$mModel = new Members;
			$member = $mModel->where(['mobile'=>$mobile])->find();
			if(empty($member)){
				return ajaxReturn('您的手机号还未注册');
			}
			if($member['is_disable']!=1){
				return ajaxReturn('账号被禁');
			}
			$code = rand(1000,9999);
			$res = SmsSend($mobile,$code);
			if($res['code'] == 0){
				session('pwdcode',$code);
				return ajaxReturn('发送成功',1);
			}else{
				return ajaxReturn($res['detail']);
			}
		}
	}
	
	public function checkmobile(){
		if(request()->isAjax()){
			$mobile = input('post.mobile');

			if(session('pwdcode') != input('post.code')){
				return ajaxReturn('短信验证码不正确');
			}

			$mModel = new Members;
			$member = $mModel->where(['mobile'=>$mobile])->find();
			if(empty($member)){
				return ajaxReturn('手机号不存在');
			}
			if($member['is_disable']!=1){
				return ajaxReturn('账号被禁');
			}
			$md5code = md5(input('post.code'));
			session($md5code,$mobile);
			return ajaxReturn("验证成功",url('Login/findpassword',['token'=>$md5code]));
		}
	}
	
	public function changewd(){
		if(request()->isAjax()){
			$mobile = input('post.mobile');
			$token  = input('post.token');
			$password = input('post.password');
			$mModel = new Members;
			$res = $mModel->where(['mobile'=>$mobile])->update(['password'=>md5($password)]);
			if($res){
				session($token,null);
				return ajaxReturn('密码修改成功',url('Login/index'));
			}else{
				return ajaxReturn('修改密码失败');
			}
		}
	}
	
	//发送短信
	public function sendcode(){
		if(request()->isAjax()){
			$mobile = input('post.mobile');
            if(!captcha_check(input('post.code'))){
                return ajaxReturn('图形验证码不正确');
            }
			$mModel = new Members;
			$info = $mModel->where(['mobile'=>$mobile])->find();
			if(!empty($info)){
				return ajaxReturn('该手机号已注册');
			}
			$code = rand(1000,9999);
			$res = SmsSend($mobile,$code);
			if($res['code'] == 0){
				session('mobilecode',$code);
				session($mobile,$code);
				return ajaxReturn('发送成功',url('Member/info'));
			}else{
				return ajaxReturn($res['detail']);
			}
		}
	}
	
}
